﻿using AutoMapper;
using FarmSmartSleep.Common.Domain.RBACFile;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;
using R.FarmSmartSleep.RBAC.API.Apliction.Command.Roless;
using System.Data;

namespace R.FarmSmartSleep.RBAC.API.Apliction.Command.Permissions
{
    /// <summary>
    /// 权限更新
    /// </summary>
    public class PermissionCreateHandler : IRequestHandler<PermissionCreateCommon, Result>
    {
        IBaseRepository<Permission> permissionRep;
        IBaseRepository<RolesPermissions> rolesPermissionsRep;
        IMapper mapper;

        public PermissionCreateHandler(IBaseRepository<Permission> permissionRep, IBaseRepository<RolesPermissions> rolesPermissionsRep, IMapper mapper)
        {
            this.permissionRep = permissionRep;
            this.rolesPermissionsRep = rolesPermissionsRep;
            this.mapper = mapper;
        }
        /// <summary>
        /// 权限更新
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(PermissionCreateCommon request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CodeEnum.update };
            try
            {
                Permission permission = mapper.Map<Permission>(request);

                /// 修改权限
                foreach (var item in request.RolesIds)
                {

                    var list = rolesPermissionsRep.GetAll().Where(c => c.RolesId == item && c.PermissionsId == request.PermissionsId);
                    if (list != null)
                    {
                        // 修改权限
                        await rolesPermissionsRep.AddAsync(new RolesPermissions
                        {
                            PermissionsId = request.PermissionsId,
                            RolesId = item
                        });
                    }
                    else
                    {
                        
                    }
                }


            }
            catch (Exception)
            {
                result.Messege = "修改失败";
                throw;
            }
            return result;
        }
    }

}
